<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片转blob</title>
    <style>
        .download {
            color: rgb(24, 144, 255);
            margin: 1vw 0 0;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <!-- 不支持本地地址下载 -->
    <input type="file" class="file">
    <div class="loading">加载中...</div>
    <div>
        <img class="img" style="max-width: 100px;max-height: 100px;margin: 1vw 0 0;">
    </div>
    <div class="downloads" onclick="toURL()">
        下载
    </div>
    <div class="box">
    </div>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.7.2/axios.min.js"></script>
    <script>
        // var file=document.querySelector('.file')
        // var img=document.querySelector('.img')
        // var loading=document.querySelector('.loading')
        // var download=document.querySelector('.download')
        // var blobs; //创建blobs对象
        // var url;
        // file.addEventListener('change',(e)=>{
        // url=URL.createObjectURL(e.target.files[0])
        // setTimeout(()=>{
        // img.src=url
        // },500)
        // })
        // img.addEventListener('load',(e)=>{
        //   if(e){
        //     loading.style.display='none'
        //   }
        // })

        //html里会涉及到跨域的问题 所以在获取接口后用画布转成blob对象然后下载
        var box = document.querySelector('.box')
        var blobs //全局定义
        //canvas toDataURL
        function toURL() {
            axios.get('http://127.0.0.1:8085/getURL').then(res => {
                var img = new Image()
                img.setAttribute('crossOrigin', 'anonymous');
                img.src = res.data.dataUrl
                img.onload = (e) => {
                    var canvas = document.createElement('canvas')
                    box.append(canvas)
                    canvas.width = 500
                    canvas.height = 300
                    var ctx = canvas.getContext('2d')
                    ctx.drawImage(img, 0, 0, 500, 300)
                    // dataURL = canvas.toDataURL('image/png');
                    // console.log(dataURL) //同源后转base
                    //转blob
                    canvas.toBlob(res=>{
                    blobs=res
                    var a=document.createElement('a')
                    var url=URL.createObjectURL(blobs)
                    a.href=url
                    a.download='下载'
                    document.body.appendChild(a)
                    a.click()
                    })
                }
            })
        }





    </script>
</body>

</html>